package com.qf.security.handlers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.cache.RoleCache;
import com.qf.dto.R;
import com.qf.events.UserLoginEvent;
import com.qf.mappers.RoleMapper;
import com.qf.pojo.BaseUser;
import com.qf.pojo.Menu;
import com.qf.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/*
杨威
2022/1/7
22:26
*/
@Component
public class MyAuthenSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RoleCache roleCache;
    @Autowired
    ApplicationContext ac;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        BaseUser baseUser = (BaseUser) authentication.getPrincipal();
        long userId = baseUser.getUserId();
        //根据用户id查询出这个用户拥有的所有的角色id
        List<Long> roleIds = roleMapper.selectRoleIdByUserId(userId);
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        roleIds.stream().forEach(roleId->{

            Role role = roleCache.getValue(roleId);
            List<Menu> menuList = role.getMenuList();
            //将权限放到一个集合里
            authorityList.addAll(menuList.parallelStream().map(Menu::getPerms).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        });

        //设置用户有什么权限
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser,authentication.getCredentials(),authorityList));
        response.setContentType("application/json;charset=utf-8");
//        ac.publishEvent(new UserLoginEvent());
        R r = R.setOk();
        response.getWriter().write(objectMapper.writeValueAsString(r));
    }
}
